package model

import (
	"errors"

	"zhejianglab/gin-apiserver/model/request"

	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
)

// AlarmInfo alarm structure
type AlarmInfo struct {
	gorm.Model
	Source         string    `json:"source"`
	CameraID       int64     `json:"camera_id"`
	Area           string    `json:"area"`
	BySecure       int64     `json:"by_secure"`
	DangerDesc     string    `json:"danger_desc"`
	DangerTypeCode int64     `json:"danger_type_code"`
	DangerTypeName string    `json:"danger_type_name"`
	DepartmentID   string    `json:"department_id"`
	DepartmentName string    `json:"department_name"`
	Images         string    `json:"images"`
	SelectSecure   int64     `json:"select_secure"`
	UUID           uuid.UUID `json:"uuid"`
}

// AddNewAlarm add a new alarm
func AddNewAlarm(r *request.AlarmInfo) error {

	GenUUID, err := uuid.NewUUID()
	if err != nil {
		return err
	}
	db.Save(&AlarmInfo{
		Source:         r.Source,
		CameraID:       r.CameraID,
		Area:           r.Area,
		BySecure:       r.BySecure,
		DangerDesc:     r.DangerDesc,
		DangerTypeCode: r.DangerTypeCode,
		DepartmentID:   r.DepartmentID,
		DepartmentName: r.DepartmentName,
		Images:         r.Images,
		SelectSecure:   r.SelectSecure,
		UUID:           GenUUID,
	})

	return nil

}

// GetAlarmWithType get a single alarm
func GetAlarmWithType(dangerTypeCode, cameraID int64) ([]AlarmInfo, error) {
	var alarm []AlarmInfo
	if dangerTypeCode == 0 {
		db.Where("camera_id = ?", cameraID).Find(&alarm)
	} else if cameraID == 0 {
		db.Where("danger_type_code = ?", dangerTypeCode).Find(&alarm)
	} else {
		db.Where("danger_type_code = ? AND camera_id = ?", dangerTypeCode, cameraID).Find(&alarm)
	}

	if len(alarm) == 0 {
		err := errors.New("no Alarm found")
		return []AlarmInfo{}, err
	}

	return alarm, nil
}

// ExistAlarmByID check the id is exist or not
func ExistAlarmByID(ID int) bool {
	var myAlarm AlarmInfo
	db.Select("id").Where("id = ?", ID).First(&myAlarm)
	if myAlarm.ID > 0 {
		return true
	}
	return false
}

// UpdateAlarm edit alarm info
func UpdateAlarm(id int, data interface{}) bool {
	db.Model(&AlarmInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteAlarm delete the alarnm info from db
func DeleteAlarm(id int) bool {
	db.Where("id = ?", id).Delete(&AlarmInfo{})

	return true
}

// GetAllAlarms get the all alarms info from db
func GetAllAlarms() (result []AlarmInfo, err error) {
	var myAlarm []AlarmInfo
	db.Find(&myAlarm)

	if len(myAlarm) == 0 {
		err = errors.New("no Alarm found")
		return nil, err
	}
	return myAlarm, nil
}
